<?php
/**
 * Created by IntelliJ IDEA.
 * User: wanglu
 * Date: 2017/9/5
 * Time: 11:05
 */

/**
 * Created by wanglu on 2017/9/5.
 */
class Project_template_service extends MY_Service
{


    public function __construct()
    {
        parent::__construct();
        $this->load->model('project_template_model');
    }


    public function add_template($pid, $name, $template, $folder, $filename, $remark) {

        $template_extis = $this->project_template_model->getRecord(array('name' => $name, 'pid'=> $pid));
        if (!empty($template_extis)) {
            throw  new AppException(ErrorCode::FAIL, " template name is exits add fail!");
        }

        $template = array(
            'pid'=> $pid,
            'name'=> $name,
            'template' => $template,
            'folder' => $folder,
            'filename' => $filename,
            'remark' => $remark,
            'createtime' => time()
        );

        return $this->project_template_model->createRecord($template);
    }

    public function get_templates_by_pid($pid) {
        //return array();
        return $this->project_template_model->getRecords(array('pid'=> $pid), array('createtime', "DESC"));
    }

    public function update_template($id, $pid, $name, $template, $folder, $filename, $remark) {
        $template_extis = $this->project_template_model->getRecord(array('id' => $id));
        if (empty($template_extis)) {
            throw  new AppException(ErrorCode::FAIL, " template  is not exits!");
        }
        //修改了缩写
        if ($template_extis['name'] != $name) {
            //查询是否有同名存在
            $name_templateextis = $this->project_template_model->getRecord(array('name' => $name, 'pid'=> $pid));
            if (!empty($name_templateextis)) {
                throw  new AppException(ErrorCode::FAIL, " template name is exits add fail, please change user template name!");
            }
        }

        $template_data = array(
            'name'=> $name,
            'template' => $template,
            'folder' => $folder,
            'filename' => $filename,
            'remark' => $remark
        );

        return $this->project_template_model->updateRecord($template_data,  array('id'=> $id));
    }

    public function delete_template($id)  {
        return $this->project_template_model->deleteRecord(array('id'=> $id));
    }


    public function get_template_by_id($id) {
        return $this->project_template_model->getRecord(array('id'=> $id));
    }
    
    

}
